# -*- coding: utf-8 -*-
import base64
import os
import time

# 好友列表显示模块

from PySide2.QtCore import QAbstractListModel, QModelIndex, Qt, QRect, QSize, Signal, QRunnable, QObject, QThreadPool, \
    QTimer, Slot
from PySide2.QtGui import QPixmap, QPalette, QBrush, QColor, QFont, QImage
from PySide2.QtWidgets import QStyledItemDelegate, QStyle, QListView

from lib import itchat

global win

class FriendListModel(QAbstractListModel):
    def __init__(self, queue_3, queue_2, index=None, friends_data=None, parent=None, page_size=100):
        super().__init__(parent)
        self.bot_index = index
        self.queue_3 = queue_3
        self.queue_2 = queue_2
        self.friends_data = friends_data or []
        self.page_size = page_size
        self.current_page = 0
        avatar_data = ''
        avatar_data = base64.b64decode(avatar_data.split(',')[1])
        self.DEFAULT_AVATAR_PATH = QImage.fromData(avatar_data)

    def rowCount(self, parent=QModelIndex()):
        return min(len(self.friends_data), (self.current_page + 1) * self.page_size)

    def data(self, index: QModelIndex, role: int = Qt.DisplayRole):
        if not index.isValid():
            return None
        friend = self.friends_data[index.row()]
        if role == Qt.DisplayRole:
            if friend['RemarkName']:
                return friend['RemarkName']
            else:
                return friend['NickName']


        elif role == Qt.DecorationRole:
            local_avatar_path = friend['Avatar']
            if local_avatar_path and os.path.exists(local_avatar_path) and os.path.getsize(local_avatar_path) > 0:
                pixmap = QPixmap(local_avatar_path)
            else:
                pixmap = QPixmap(self.DEFAULT_AVATAR_PATH)
            return pixmap.scaledToHeight(50)

        elif role == Qt.UserRole + 1:
            msg_type = friend['Msg'].get('type')
            if msg_type == "PICTURE":
                return "[图片]"
            else:
                return friend['Msg'].get('content', '')

        elif role == Qt.UserRole + 2:
            return friend['Msg'].get('time', '')
        return None

    def load_more(self):
        self.beginInsertRows(QModelIndex(), self.rowCount(), self.rowCount() + self.page_size - 1)
        self.current_page += 1
        self.endInsertRows()

    def update_friends_data(self, new_friends_data):
        self.beginResetModel()
        self.friends_data = new_friends_data
        self.current_page = 0
        self.endResetModel()

    def get_friends_data(self):
        return self.friends_data

    # def cleanup(self):
    #     pass
    #
    # def __del__(self):
    #     self.cleanup()
    #
    # def closeEvent(self, event):
    #     self.cleanup()
    #     super().closeEvent(event)


class FriendItemDelegate(QStyledItemDelegate):
    def paint(self, painter, option, index):
        painter.save()

        color_group = QPalette.Active if option.state & QStyle.State_Active else QPalette.Inactive
        color_role = QPalette.Highlight if option.state & QStyle.State_Selected else QPalette.Window
        brush = QBrush(option.palette.color(color_group, color_role))
        painter.fillRect(option.rect, brush)

        # 根据选中状态改变背景色
        if option.state & QStyle.State_Selected:
            painter.fillRect(option.rect, QColor(201, 199, 198))  # 选中状态的背景色

        # 根据鼠标悬停状态改变文本颜色
        if option.state & QStyle.State_MouseOver:
            painter.setPen(QColor(0, 0, 255))  # 鼠标悬停时的文本颜色

        # 设置字体和颜色
        font = QFont()
        nickname_color = QColor('black')
        message_color = QColor('gray')
        time_color = QColor('gray')

        # 绘制头像
        avatar = index.data(Qt.DecorationRole)
        avatar_rect = QRect(option.rect.x() + 10, option.rect.y() + 10, 40, 40)
        painter.drawPixmap(avatar_rect, avatar)

        # 绘制昵称
        nickname = index.data(Qt.DisplayRole)
        nickname_rect = QRect(option.rect.x() + 60, option.rect.y() + 10, option.rect.width() - 80, 20)
        font.setPointSize(11)
        painter.setFont(font)
        painter.setPen(nickname_color)
        painter.drawText(nickname_rect, Qt.AlignVCenter, nickname)

        # 绘制最后一条消息
        message = index.data(Qt.UserRole + 1)
        message_rect = QRect(option.rect.x() + 60, option.rect.y() + 30, option.rect.width() - 80, 20)
        font.setPointSize(9)
        painter.setFont(font)
        painter.setPen(message_color)
        painter.drawText(message_rect, Qt.AlignVCenter, message)

        # 绘制最后一条消息的时间
        time = index.data(Qt.UserRole + 2)
        time_rect = QRect(option.rect.right() - 80, option.rect.y() + 10, 70, 20)
        font.setPointSize(9)
        painter.setFont(font)
        painter.setPen(time_color)
        painter.drawText(time_rect, Qt.AlignRight | Qt.AlignVCenter, time)

        painter.restore()

    def sizeHint(self, option, index):
        # return QSize(200, 65)  # 返回每个列表项的推荐尺寸
        return QSize(230, 60)

    # def cleanup(self):
    #     pass
    #
    # def __del__(self):
    #     self.cleanup()
    #
    # def closeEvent(self, event):
    #     self.cleanup()
    #     super().closeEvent(event)


class FriendListView(QListView):
    clicked = Signal(int, int)  # 信号，参数为好友的索引

    def __init__(self, index, queue_3, queue_2, friends_data=None, parent=None):
        super().__init__(parent)
        self.index = index
        self.model = FriendListModel(queue_3, queue_2, index=self.index, friends_data=friends_data)
        self.delegate = FriendItemDelegate(self)
        self.setItemDelegate(self.delegate)
        self.setModel(self.model)
        self.setFrameShape(QListView.NoFrame)
        self.viewport().setContentsMargins(0, 0, 0, 0)
        self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        # 定义滚动条的样式
        scrollbar_style = """
            QScrollBar:vertical {
                border: none;
                background: transparent;
                width: 5px;
                opacity: 0.0;
                border-radius: 20px;
            }
            QScrollBar:hover:vertical {
                opacity: 1.0;
            }
            QScrollBar::handle:vertical {
                background: #aeabaa;
                min-height: 20px;
            }
            QScrollBar::add-line:vertical {
                height: 0px;
            }
            QScrollBar::sub-line:vertical {
                height: 0px;
            }
            QScrollBar::up-arrow:vertical, QScrollBar::down-arrow:vertical {
                border: none;
                width: 1px;
                height: 1px;
                background: none;
            }
            QScrollBar::add-page:vertical, QScrollBar::sub-page:vertical {
                background: none;
            }
        """
        # 应用样式
        self.setStyleSheet(scrollbar_style)
        # 设置滚动条策略为仅在需要时出现
        self.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded)
        self.setHorizontalScrollBarPolicy(Qt.ScrollBarAsNeeded)

        self.friends_data = []

        self.viewport().installEventFilter(self)

    def eventFilter(self, obj, event):
        if event.type() == event.Resize and obj is self.viewport():
            if self.verticalScrollBar().value() == self.verticalScrollBar().maximum():
                self.model.load_more()
        return super().eventFilter(obj, event)

    # def cleanup(self):
    #     # 清理FriendListModel实例
    #     self.model.cleanup()
    #     self.model.deleteLater()
    #
    #     self.delegate.cleanup()
    #     self.delegate.deleteLater()
    #
    # def  __del__(self):
    #     self.cleanup()
    #
    # def closeEvent(self, event):
    #     self.cleanup()
    #     super().closeEvent(event)

    def mousePressEvent(self, event):
        # 重写mousePressEvent处理点击事件
        index = self.indexAt(event.pos())
        if index.isValid():
            self.clicked.emit(self.index, index.row())  # 发射信号，传入选中好友的索引
        super().mousePressEvent(event)
